import {
  Button,
  Form,
  Message,
  Modal,
  Select,
  Space,
} from "@arco-design/web-react";
import { FC } from "react";
import { useAPI } from "../../hooks/useAPI.ts";
import {
  Role,
  SystemUserDataRow,
  SystemUserParams,
} from "../../api/types/system-user.ts";
import { useMutation, useQuery } from "react-query";
import { css } from "@emotion/css";
import { IconCheck, IconClose } from "@arco-design/web-react/icon";

export interface BindingBuildingAdminModalProps {
  visible: boolean;
  onClose?: () => void;
  onSuccess?: () => void;
  title?: string;
  defaultData?: SystemUserDataRow;
}

export const BindingBuildingAdminModal: FC<BindingBuildingAdminModalProps> = ({
  visible,
  onClose,
  title,
  onSuccess,
  defaultData,
}) => {
  const api = useAPI();
  const { data: userList } = useQuery(
    ["query-user-list"],
    async () => {
      try {
        const response = await api.getSystemUserList_({
          key: "",
          roleIds: Role.BuildingAdmin,
          pageNum: 1,
          pageSize: 100000,
        });
        return response.data.data.rows;
      } catch (error) {
        if (error instanceof Error) {
          Message.error(error.message);
        } else {
          Message.error("操作失败，请稍后重试");
        }
      }
    });
  const { data: buildingList } = useQuery(["getBuildingList"], async () => {
    try {
      const response = await api.getBuildingList({
        pageNum: 1,
        pageSize: 1000,
      });
      return response.data.data.rows;
    } catch (error) {
      if (error instanceof Error) {
        Message.error(error.message);
      } else {
        Message.error("操作失败，请稍后重试");
      }
    }
  });
  const [formRef] = Form.useForm<SystemUserDataRow>();
  const submitForm = useMutation(async () => {
    try {
      const values = await formRef.validate();
      const { data } = (await api.getSystemUserInfoById(values.userId)).data;
      await api.updateSystemUser({
        ...(data as unknown as SystemUserParams),
        roleIds: [Role.BuildingAdmin],
        buildingId: values.buildingId,
      });
      formRef.resetFields();
      onSuccess?.();
      Message.success("操作成功");
    } catch (error) {
      if (error instanceof Error) {
        Message.error(error.message);
      } else {
        Message.error("操作失败，请稍后重试");
      }
    }
  });
  return (
    <Modal
      visible={visible}
      onCancel={() => {
        formRef.resetFields();
        onClose?.();
      }}
      footer={null}
      title={title}
      unmountOnExit
      mountOnEnter
    >
      <Form form={formRef} initialValues={defaultData}>
        <Form.Item
          label="楼管"
          field="userId"
          rules={[
            {
              required: true,
              message: "请选择楼管",
            },
          ]}
        >
          <Select
            placeholder="请选择要添加的楼管"
            filterOption={(input, option) =>
              option?.props.children.toLowerCase().includes(input.toLowerCase())
            }
            options={userList?.map((v) => ({
              label: v.nickName,
              value: v.userId,
            }))}
          />
        </Form.Item>
        <Form.Item
          label="楼栋"
          field="buildingId"
          rules={[
            {
              required: false,
              message: "请选择楼栋",
            },
          ]}
        >
          <Select
            placeholder="请选择楼栋"
            options={buildingList?.map((v) => ({
              label: v.name,
              value: v.id,
            }))}
          ></Select>
        </Form.Item>
        <Space
          className={css`
            margin-top: 16px;
            padding: 12px 0;
            display: flex;
            justify-content: end;
          `}
        >
          <Button
            type="outline"
            htmlType="button"
            onClick={() => {
              formRef.resetFields();
              onClose?.();
            }}
            icon={<IconClose />}
          >
            取消
          </Button>
          <Button
            type="primary"
            htmlType="submit"
            loading={submitForm.isLoading}
            onClick={() => submitForm.mutateAsync()}
            icon={<IconCheck />}
          >
            完成
          </Button>
        </Space>
      </Form>
    </Modal>
  );
};
